<template>
    <div class="system-dept-dialog-container">
        <el-dialog :title="dataForm.id ? $t('common.editBtn') : $t('common.addBtn')" v-model="visible" width="600">
            <el-form ref="deptDialogFormRef" :model="dataForm" label-width="90px" :rules="dataRules" v-loading="loading">
                <el-form-item :label="$t('atlas.relationId')" prop="relationId">
                    <el-tree-select
                            v-model="dataForm.relationId"
                            :data="parentData"
                            :props="{ value: 'id', label: 'name', children: 'children' }"
                            class="w100"
                            clearable
                            check-strictly
                            :render-after-expand="false"
                            :placeholder="$t('atlas.inputparentIdTip')"
                    />
                </el-form-item>
                <el-form-item :label="$t('atlas.datasourceName')" prop="datasourceId">
                    <el-select v-model="dataForm.datasourceId" placeholder="请选择数据源" @change="onDatasourceChange">
                        <el-option v-for="option in bindingOptions" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('atlas.tableName')" prop="tableName">
                    <el-select v-model="dataForm.tableName" placeholder="请选择表" @change="onTableChange">
                        <el-option v-for="option in tableData" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('atlas.filedName')" prop="filedName">
                    <el-select v-model="dataForm.filedName" placeholder="请选择表字段" @change="onFieldChange">
                        <el-option v-for="option in filedData" :key="option.value" :label="option.label" :value="option.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('atlas.sortOrder')" prop="sortOrder">
                    <el-input-number v-model="dataForm.sortOrder" :placeholder="$t('atlas.sortOrder')" clearable />
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
          <el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
        </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="systemDeptDialog">
    import { useI18n } from 'vue-i18n';
    import { getObj, relationTree, addObj, putObj, dataSource, fetchTables, fetchFields } from '/@/api/know/relation';
    import { useMessage } from '/@/hooks/message';

    // 定义发射事件
    const emit = defineEmits(['refresh']);
    const { t } = useI18n();

    // 定义变量
    const deptDialogFormRef = ref();
    const bindingOptions = ref([]);
    const tableData = ref([]);
    const filedData = ref([]);

    const router = useRouter();
    const route = useRoute();
    const dataForm = reactive({
        id: '',
        datasourceName: '',
        sortOrder: 9999,
        datasourceId: '',
        tableName: '',
        tableSchema: '',
        filedName: '',
        filedSchema: '',
        relationId: '',
        topoId: route.query.topoId || '',
    });

    const parentData = ref<any[]>([]);
    const visible = ref(false);
    const loading = ref(false);

    const dataRules = ref({
        // 添加必要的验证规则
    });

    // 获取表数据
    const fetchTableData = (datasourceName: string) => {
        if (!datasourceName) {
            tableData.value = [];
            return;
        }
        fetchTables(datasourceName).then((res: any) => {
            console.log(res);
            if (Array.isArray(res.data)) {
                tableData.value = res.data.map((item: any) => ({
                    label: item.tableComment,
                    value: item.tableName, // 假设您需要表名来获取字段
                }));
            } else {
                console.error('Unexpected data structure:', res);
            }
        }).catch((error: any) => {
            console.error('Failed to fetch table data:', error);
        });
    };

    // 获取字段数据
    const fetchFieldData = (datasourceName: string, tableName: string) => {
        if (!datasourceName || !tableName) {
            filedData.value = [];
            return;
        }
        fetchFields(datasourceName, tableName).then((res: any) => {
            if (Array.isArray(res.data.fieldList)) {
                filedData.value = res.data.fieldList.map((item: any) => ({
                    label: item.fieldComment,
                    value: item.attrName,
                }));
            } else {
                console.error('Unexpected data structure:', res);
            }
        }).catch((error: any) => {
            console.error('Failed to fetch field data:', error);
        });
    };

    // 处理数据源更改
    const onDatasourceChange = (value: string) => {
        if (!value) return;
        const selectedOption = bindingOptions.value.find(option => option.value === value);
        if (selectedOption) {
            fetchTableData(selectedOption.label);
            dataForm.datasourceName = selectedOption.label; // 保存数据源的 label
            dataForm.tableName = '';
            dataForm.tableSchema = '';
            dataForm.filedName = '';
            dataForm.filedSchema = '';
            tableData.value = [];
            filedData.value = [];
        }
    };

    // 处理表格更改
    const onTableChange = (value: string) => {
        if (!value) return;
        const selectedDatasource = bindingOptions.value.find(option => option.value === dataForm.datasourceId);
        if (selectedDatasource) {
            fetchFieldData(selectedDatasource.label, value);
            const selectedTable = tableData.value.find(option => option.value === value);
            if (selectedTable) {
                dataForm.tableSchema = selectedTable.label; // 保存表的 label
            }
            dataForm.filedName = '';
            dataForm.filedSchema = '';
            filedData.value = [];
        }
    };

    // 处理字段更改
    const onFieldChange = (value: string) => {
        const selectedField = filedData.value.find(option => option.value === value);
        if (selectedField) {
            dataForm.filedSchema = selectedField.label; // 保存字段的 label
        }
    };

    // 打开对话框
    const openDialog = (type: string, id: string) => {
        visible.value = true;
        dataForm.id = '';

        // 获取数据源选项
        dataSource().then((res: any) => {
            if (Array.isArray(res.data)) {
                bindingOptions.value = res.data.map((item: any) => ({
                    label: item.name,
                    value: item.id,
                }));
            } else {
                console.error('意外的数据结构:', res);
            }
        }).catch((error: any) => {
            console.error('无法获取绑定数据:', error);
        });

        nextTick(() => {
            deptDialogFormRef.value?.resetFields();
            if (type === 'add') {
                dataForm.topoId = route.query.topoId || '';
            } else {
                dataForm.relationId = id;
            }
        });

        if (type === 'edit') {
            getObj(id)
                .then((res) => {
                    Object.assign(dataForm, res.data);
                })
                .catch((err) => {
                    useMessage().error(err.msg);
                });
        }

        getDeptData(dataForm.topoId);
    };

    // 提交表单
    const onSubmit = async () => {
        const valid = await deptDialogFormRef.value.validate().catch(() => { });
        if (!valid) return false;
        console.log(dataForm);
        try {
            loading.value = true;
            dataForm.id ? await putObj(dataForm) : await addObj(dataForm);
            useMessage().success(t(dataForm.id ? 'common.editSuccessText' : 'common.addSuccessText'));
            visible.value = false;
            emit('refresh');
        } catch (err: any) {
            useMessage().error(err.msg);
        } finally {
            loading.value = false;
        }
    };

    // 获取图谱数据
    const getDeptData = async (topoId: String) => {
        relationTree({topoId}).then((res) => {
            parentData.value = [];
            const dept = {
                id: '0',
                name: '根图谱',
                children: [] as any[],
            };
            dept.children = res.data;
            parentData.value.push(dept);
        });
    };

    // 公开变量
    defineExpose({
        openDialog,
    });
</script>
